package top.yangyitao.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import top.yangyitao.dto.AttendanceRecordDto;
import top.yangyitao.dto.ResultDto;
import top.yangyitao.dto.TableDto;
import top.yangyitao.entity.AttendanceRecord;
import top.yangyitao.entity.User;
import top.yangyitao.service.AttendanceRecordService;
import top.yangyitao.service.UserService;

@RestController
public class AttendanceRecordController {
	@Autowired
	AttendanceRecordService attendanceRecordService;
	
	@Autowired
	UserService userService;
	
	@RequiresPermissions("attendanceRecord_html")
	@RequestMapping("/attendanceRecord_html")
	public ModelAndView attendanceRecord_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/attendanceRecord.html");
		return mv;
	}
	
	@RequiresPermissions("attendanceRecord_html")
	@RequestMapping("/addAttendanceRecord")
	public ResultDto addAttendanceRecord(String username,String checkTime_day,String checkTime_time) {
		User user = userService.findByUsername(username);
		if(user!=null) {
			String checkTime = checkTime_day+" "+checkTime_time;
			AttendanceRecord attendanceRecord = new AttendanceRecord();
			attendanceRecord.setCheckTime(checkTime);
			attendanceRecord.setUser(user);
			attendanceRecordService.save(attendanceRecord);
			return new ResultDto("添加打卡记录成功",null,0);
		}
		else {
			return new ResultDto("用户名不存在",null,2);
		}
	}

	
	@RequiresPermissions("attendanceRecord_html")
	@RequestMapping("/getAttendanceRecordPage")
	public TableDto<AttendanceRecordDto> getAttendanceRecordPage(Integer pageNumber,Integer pageSize,Long organizationId,String startDay,String endDay,String search) {
		Page<AttendanceRecord> pageResult = attendanceRecordService.getAttendanceRecordPage(pageNumber,pageSize,organizationId,null,startDay,endDay,search);
		List<AttendanceRecord> attendanceRecords = pageResult.getContent();
		List<AttendanceRecordDto> attendanceRecordDtos = new ArrayList<AttendanceRecordDto>();
		attendanceRecords.forEach(attendanceRecord->attendanceRecordDtos.add(new AttendanceRecordDto().convert(attendanceRecord)));
		return new TableDto<AttendanceRecordDto>(attendanceRecordDtos,pageResult.getTotalElements());
	}
}
